<template>
  <div class="education-summary">
    <div class="panel">
      <div class="panel-title">近期知识点掌握概览</div>
      <div class="mastery-list">
        <div v-for="(m, i) in masteryTop" :key="i" class="mastery-item">
          <span class="name">{{ m.point }}</span>
          <d-progress :percentage="m.rate" :show-text="true"></d-progress>
        </div>
      </div>
    </div>
    <div class="panel">
      <div class="panel-title">常见错误类型统计</div>
      <div class="errors">
        <span v-for="(e, i) in errorStat" :key="i" class="pill warn">{{ e.name }} {{ e.count }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useChatMessageStore } from '@/store';
import type { IMessage } from '@/types';
const msgStore = useChatMessageStore();

const assistantMessages = computed(() => msgStore.messages.filter((m: IMessage) => m.from === 'assistant' && m.complete));

const masteryTop = computed(() => {
  const map = new Map<string, number[]>();
  assistantMessages.value.forEach((m) => {
    m.education?.mastery?.forEach(({ point, rate }) => {
      const arr = map.get(point) || [];
      arr.push(rate);
      map.set(point, arr);
    });
  });
  const list = Array.from(map.entries()).map(([point, arr]) => ({ point, rate: Math.round(arr.reduce((a, b) => a + b, 0) / arr.length) }));
  const sample = [
    { point: '二次函数', rate: 60 },
    { point: '时态用法', rate: 45 },
    { point: '网络分析', rate: 55 },
  ];
  return list.length ? list.slice(0, 5) : sample;
});

const errorStat = computed(() => {
  const map = new Map<string, number>();
  assistantMessages.value.forEach((m) => {
    m.education?.errorTypes?.forEach((et) => {
      map.set(et, (map.get(et) || 0) + 1);
    });
  });
  const list = Array.from(map.entries()).map(([name, count]) => ({ name, count }));
  const sample = [
    { name: '概念混淆', count: 3 },
    { name: '计算错误', count: 2 },
    { name: '步骤遗漏', count: 1 },
  ];
  return list.length ? list : sample;
});
</script>

<style scoped lang="scss">
@import "devui-theme/styles-var/devui-var.scss";

.education-summary {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}

.panel {
  background-color: $devui-base-bg;
  border: 1px solid $devui-line;
  box-shadow: 0px 6px 20px 0px rgba(25, 25, 25, 0.08);
  border-radius: 12px;
  padding: 16px;
}

.panel-title {
  font-size: 15px;
  font-weight: 600;
  color: $devui-text;
  margin-bottom: 12px;
}

.mastery-item {
  display: grid;
  grid-template-columns: 140px 1fr;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.name {
  color: $devui-text;
}

.errors {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pill {
  display: inline-flex;
  align-items: center;
  padding: 6px 10px;
  border-radius: 999px;
  background-color: $devui-gray-10;
  color: $devui-text;
  font-size: 12px;
}

.pill.warn {
  background-color: $devui-warning-bg;
  color: $devui-warning;
}
</style>